/**
 * @description router全局配置，如有必要可分文件抽离，其中asyncRoutes只有在intelligence模式下才会用到，pro版只支持remixIcon图标，具体配置请查看vip群文档
 */
import type { VabRouteRecordRaw } from './types'
import type { RouteRecordRaw } from 'vue-router'
import type { App } from 'vue'
import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
  RouteRecordName,
} from 'vue-router'
import { authentication, isHashRouterMode, base } from '/@/config'
import { setupPermissions } from '/@/router/permissions'
import { modulesFiles } from './module'
import constantRouter from './constantRoutes'
// 基础页面 登录、注册 403、404
export const constantRoutes: VabRouteRecordRaw[] = constantRouter
// 本地页面
export const asyncRoutes: VabRouteRecordRaw[] = modulesFiles

//创建路由管理规则 默认hash模式
const router = createRouter({
  history: isHashRouterMode
    ? createWebHashHistory(base)
    : createWebHistory(base),
  // history: createWebHistory(base),
  routes: constantRoutes as RouteRecordRaw[],
})
function fatteningRoutes(routes: VabRouteRecordRaw[]): VabRouteRecordRaw[] {
  return routes.flatMap((route) => {
    return route.children ? fatteningRoutes(route.children) : route
  })
}

//追加路由 类似线上路由和本地路由合并
function addRouter(routes: VabRouteRecordRaw[]) {
  routes.forEach((route: VabRouteRecordRaw) => {
    if (!router.hasRoute(route.name)) router.addRoute(route as RouteRecordRaw)
    if (route.children) addRouter(route.children)
  })
}
// 重置路由
export function resetRouter(routes: VabRouteRecordRaw[] = constantRoutes) {
  routes.map((route: VabRouteRecordRaw) => {
    if (route.children) {
      route.children = fatteningRoutes(route.children)
    }
  })
  router.getRoutes().forEach((route) => {
    if (route.name) {
      const routeName: RouteRecordName = route.name
      router.hasRoute(routeName) && router.removeRoute(routeName)
    }
  })
  addRouter(routes)
}

export function setupRouter(app: App<Element>) {
  if (authentication === 'intelligence') addRouter(asyncRoutes)
  setupPermissions(router)
  app.use(router)
  return router
}

export default router
